package com.cheng.service.FaceService;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cheng.mapper.ClassMapper;
import com.cheng.mapper.UserMapper;
import com.cheng.pojo.*;
import com.cheng.pojo.Class;
import com.cheng.utli.DateTime;
import com.cheng.utli.RedisUtil;
import com.cheng.utli.Utils;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import static com.cheng.controller.Constant.CLASS_SIGN_NUMBER;
import static com.cheng.service.FaceService.UserServiceConstant.*;
@Service
public class TeacherServiceImpl implements TeacherService{

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private ClassMapper classMapper;

    @Autowired
    private RedisUtil redisUtil;

    private static final Logger logger = LoggerFactory.getLogger(TeacherServiceImpl.class);

    @Override
    public String addClass(HashMap<String, String> classInfo) {
        //根据openId得到tid
        Teacher teacher = userMapper.getTeacher(classInfo.get("openId"));
        logger.info("teacher>>>>>>>>>"+teacher);
        //创建班级
        String cid = Utils.randomString().substring(0,5);
        classInfo.remove("openId");
        classInfo.put("cid",cid);
        classInfo.put("tid",teacher.getTid());
        //创建班级操作
        classMapper.addClass(classInfo);

        HashMap<String,String> info = new HashMap<String,String>();
        info.put("userId",teacher.getTid());
        info.put("name",teacher.getName());
        info.put("cid",cid);
        info.put("power","0");
        info.put("state","0");

        //将老师的信息加入班级表
        classMapper.joinClass(info);
        return cid;
    }

    @Override
    public JSONObject startSignIn(String cid, String type) {
        JSONObject returnObj = new JSONObject();
        //获得签到类型  1.开启人脸签到 2.开启随机密码签到  3.开启九宫格签到
        if(("1").equals(type)){
            returnObj.put("type","1");
        }
        else if(("2").equals(type)){
            //获得随机密码
            returnObj.put("type","2");
        }
        else if(("3").equals(type)){
            returnObj.put("type","3");
        }
        //获得当前班级的所以学生
        List<Class> allClass = classMapper.allClass(cid);
        //通过cid得到当前班级信息
        ClassRecord classInfo = classMapper.getClassInfo(cid);

        //得到当前时间

        HashMap<String,String> singInfo = new HashMap<String,String>();
        String today = DateTime.getTimestamp("yyyyMMdd");
        //使用redis缓存 获得签到次数
        String key = redisUtil.formatRedisKey(CLASS_SIGN_NUMBER,cid);
        String number = "";
        if(redisUtil.exists(key)){
            redisUtil.incrBy(key);
            //得到key值
            number = (String) redisUtil.get(key);
            logger.info("当前得到班级签到次数为:"+number);
        }else{
            //缓存中没有值，创建该值
            redisUtil.set(key,"1");
            number = (String) redisUtil.get(key);
        }
        //使用redis缓存 获得签到次数次数
        for (Class user:allClass) {

            //入签到表参数
            singInfo.put("cid",cid);
            singInfo.put("cname",classInfo.getcName());
            singInfo.put("sid",user.getUserID());
            singInfo.put("name",user.getName());
            singInfo.put("date",today);
            singInfo.put("number",number);
            singInfo.put("state","0");
            classMapper.addSingIn(singInfo);
        }

        returnObj.put("resCode","100");
        return returnObj;
    }

    /**
     * 老师通过cid获取本次课的签到
     * */
    public JSONObject queryByCidSignIn(String cid) throws ParseException {
        JSONObject result = new JSONObject();

        List<ClassSignList> classSignLists =  classMapper.queryByCidSignIn(cid);
        //得到当前班级签到的次数
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy年MM月dd日");
        for(ClassSignList classSignList:classSignLists){
            SimpleDateFormat formatter=new SimpleDateFormat("yyyyMMdd");
            Date date=formatter.parse(classSignList.getDate());

            String format = sdf.format(date);
            classSignList.setDate(format);
        }

        result.put("signInCount",classSignLists.size());
        result.put("info",classSignLists);

        return result;
    }

    /**
     *获取某一次的具体信息
     * @param cid
     * @param number
     * @return
     */
    public JSONObject queryClassDetailSignInfo(String cid ,String number){
        JSONArray signArray = new JSONArray();
        JSONArray noSignArray = new JSONArray();
        JSONArray leaveArray = new JSONArray();


        //根据cid，number得到本次签到信息
        List<SignIn> SignInfo =  classMapper.getUserSignInfo(cid,number);

        for (SignIn signIn:SignInfo) {
            JSONObject userInfo = new JSONObject();
            userInfo.put("name",signIn.getName());
            userInfo.put("signInTime",signIn.getSignInTime());
            userInfo.put("sid",signIn.getSid());
            userInfo.put("state",signIn.getState());
            if(signIn.getState().equals(SIGN)){
                signArray.add(userInfo);
            }else if(signIn.getState().equals(NOSIGN)){
                noSignArray.add(userInfo);
            }else if(signIn.getState().equals(LEAVE)){
                leaveArray.add(userInfo);
            }
        }
        JSONObject result = new JSONObject();
        result.put("signInfo",signArray);
        result.put("noSignInfo",noSignArray);
        result.put("leaveInfo",leaveArray);

        return result;
    }

    @Override
    public JSONObject checkLeaveState(String openId) {
        JSONObject result = new JSONObject();
        Teacher teacher = userMapper.getTeacher(openId);

        //得到教师创建的班级下是否存在未审批的请假
        List<LeaveInfo> leaveInfo = userMapper.checkLeaveState(teacher.getTid());

        if(leaveInfo.isEmpty()){
            return null;
        }
        result.put("leaveInfo",leaveInfo);
        return result;
    }

    /**
     *修改请假状态
     * @param leaveInfo
     * @return
     */
    @Override
    public void updateLeaveState(HashMap<String, String> leaveInfo, String cid) {
        userMapper.updateLeaveState(leaveInfo);
        //修改签到表
        String sid = userMapper.byLogIdGetSid(leaveInfo.get("logId"));
        //修改签到表
        userMapper.updateLeaveUser(sid,cid);
    }

    @Override
    public JSONObject getTeacherCreateClass(String openId) {
        JSONObject result = new JSONObject();
        Teacher teacher = userMapper.getTeacher(openId);
        //得到用户所有的班级操作
        List<ClassRecord> classList = userMapper.getTeacherCreateClass(teacher.getTid());

        result.put("classList",classList);
        result.put("tid",teacher.getTid());
        return result;
    }
    @Override
    public JSONObject getUserSignInfo(String cid) {
        JSONObject result = new JSONObject();
        JSONObject userInfo = new JSONObject();
        JSONArray userArray = new JSONArray();

        String key = redisUtil.formatRedisKey(CLASS_SIGN_NUMBER,cid);
        String number = (String) redisUtil.get(key);

        return queryClassDetailSignInfo(cid,number);
    }

    @Override
    public JSONObject getClassInfo(String cid){
        ClassRecord classRecord = classMapper.getClassInfo(cid);
        JSONObject result = new JSONObject();
        result.put("name",classRecord.getcName());
        return result;
    }

    @Override
    public boolean checkTeacher(String tid) {
        Teacher teacher = userMapper.getTeacherTid(tid);

        if(teacher ==null){
            return false;
        }
         return true;
    }

    @Override
    public JSONObject getUserInfo(String openId) {
        JSONObject result = new JSONObject();
        Teacher teacher = userMapper.getTeacher(openId);

        result.put("tid",teacher.getTid());
        result.put("name",teacher.getName());

        return result;
    }

    @Override
    public boolean updateUserInfo(String name,String openId) {
        HashMap<String,String> userinfo = new HashMap<String,String>();
        userinfo.put("name",name);
        userinfo.put("openId",openId);
        return userMapper.updateTeacherInfo(userinfo)>0;
    }

    @Override
    public JSONArray getClassStudent(String cid) {
        JSONArray classList = new JSONArray();
        List<Class> allClass = classMapper.allClass(cid);
        //使用redis缓存 获得签到次数次数
        for (Class user:allClass) {
            JSONObject merber = new JSONObject();
            //入签到表参数
            merber.put("uid",user.getUserID());
            merber.put("name",user.getName());
            classList.add(merber);
        }
        return  classList;
    }

    @Override
    public JSONObject getPageClassStudent(JSONObject info, int page) {
        JSONArray jsonArray = new JSONArray();
        JSONObject result  = new JSONObject();
        int end = page*10;
        int begin = (page-1)*10;
        if(end>info.getJSONArray("info").size()){
            end = info.getJSONArray("info").size();
        }
        for (int i=begin;i<end;i++){
            jsonArray.add(info.getJSONArray("info").getJSONObject(i));
        }
        result.put("info",jsonArray);
        return  result;
    }



    /**
     * 得到当前班级的所有签到记录
     * @param openId
     * @return
     */
    @Override
    public JSONObject
    getLeaveList(String cid,String openId) throws ParseException {
        JSONObject result = new JSONObject();
        Teacher teacher = userMapper.getTeacher(openId);
        JSONArray leaveArray = new JSONArray();
        JSONArray noLeaveArray = new JSONArray();
        //得到教师创建的班级下是否存在未审批的请假
        List<LeaveInfo> leaveInfoList = userMapper.getLeaveList(cid);
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy年MM月dd日");

        for(LeaveInfo leaveInfo:leaveInfoList){
            SimpleDateFormat formatter=new SimpleDateFormat("yyyyMMdd");
            Date date=formatter.parse(leaveInfo.getToday());

            String format = sdf.format(date);
            leaveInfo.setToday(format);
            if(leaveInfo.getState().equals("1")||leaveInfo.getState().equals("2")){
                leaveArray.add(leaveInfo);
            }else{
                noLeaveArray.add(leaveInfo);
            }
        }
        result.put("leaveInfo",leaveArray);
        result.put("noLeaveInfo",noLeaveArray);
        return result;
    }

    @Override
    public Workbook exportSignInList(String cid, String number) {
        JSONObject result =  queryClassDetailSignInfo(cid, number);

        String[] excelHeader={"学号","姓名","签到时间","签到状态"};
        Workbook wb = new SXSSFWorkbook(1000);

        Sheet sheet = (Sheet) wb.createSheet("Sheet1");//创建工作表
        Row row = sheet.createRow(0);  //创建行，从0开始
        CellStyle style = wb.createCellStyle();
        style.setAlignment(HorizontalAlignment.CENTER);  //对齐方式

        //导入头部
        for (int i = 0; i < excelHeader.length; i++) {

            Cell cell = row.createCell(i);
            cell.setCellValue(excelHeader[i]);
            cell.setCellStyle(style);
            sheet.setColumnWidth(1, (short) 6000);  //设置列宽
            sheet.setColumnWidth(2, (short) 15000);  //设置列宽
        }
        JSONArray signArray = result.getJSONArray("signInfo");
        JSONArray noSignArray =result.getJSONArray("noSignInfo");
        JSONArray leaveArray = result.getJSONArray("leaveInfo");
        int count = 0;
        for(int i=0 ; i<signArray.size();i++){
            row = sheet.createRow(count + 1);
            count++;
            JSONObject info = signArray.getJSONObject(i);
            row.createCell(0).setCellValue(info.getString("sid"));   //设置单元格内容
            row.createCell(1).setCellValue(info.getString("name"));
            row.createCell(2).setCellValue(info.getString("signInTime"));
            row.createCell(3).setCellValue("已签到");
        }
        for(int i=0 ; i<noSignArray.size();i++){
            row = sheet.createRow(count + 1);
            count++;
            JSONObject info = noSignArray.getJSONObject(i);
            row.createCell(0).setCellValue(info.getString("sid"));   //设置单元格内容
            row.createCell(1).setCellValue(info.getString("name"));
            row.createCell(2).setCellValue(info.getString("signInTime"));
            row.createCell(3).setCellValue("未签到");
        }
        for(int i=0 ; i<leaveArray.size();i++){
            row = sheet.createRow(count + 1);
            count++;
            JSONObject info = leaveArray.getJSONObject(i);
            row.createCell(0).setCellValue(info.getString("sid"));   //设置单元格内容
            row.createCell(1).setCellValue(info.getString("name"));
            row.createCell(2).setCellValue(info.getString("signInTime"));
            row.createCell(3).setCellValue("请假");
        }
        return wb;
    }

    @Override
    public Workbook exportSignInListAllClass(String cid) {
        //根据cid查询当前的签到次数
        String key = redisUtil.formatRedisKey(CLASS_SIGN_NUMBER,cid);

        int number = Integer.parseInt(redisUtil.getString(key));
        Workbook wb = new SXSSFWorkbook(1000);

        Sheet[] sheet = new Sheet[number];
        //遍历查询得到数据
        for(int i=1 ; i<=number;i++){
            sheet[i-1] = wb.createSheet("第"+i+"次签到");
        }

        for(int j=1 ;j<=number;j++){
            JSONObject result =  queryClassDetailSignInfo(cid, String.valueOf(j));
            String[] excelHeader={"学号","姓名","签到时间","签到状态"};

            Row row = sheet[j-1].createRow(0);  //创建行，从0开始
            CellStyle style = wb.createCellStyle();
            style.setAlignment(HorizontalAlignment.CENTER);  //对齐方式

            //导入头部
            for (int i = 0; i < excelHeader.length; i++) {

                Cell cell = row.createCell(i);
                cell.setCellValue(excelHeader[i]);
                cell.setCellStyle(style);
                sheet[j-1].setColumnWidth(1, (short) 6000);  //设置列宽
                sheet[j-1].setColumnWidth(2, (short) 10000);  //设置列宽
            }
            JSONArray signArray = result.getJSONArray("signInfo");
            JSONArray noSignArray =result.getJSONArray("noSignInfo");
            JSONArray leaveArray = result.getJSONArray("leaveInfo");
            int count = 0;
            for(int i=0 ; i<signArray.size();i++){
                row = sheet[j-1].createRow(count + 1);
                count++;
                JSONObject info = signArray.getJSONObject(i);
                row.createCell(0).setCellValue(info.getString("sid"));   //设置单元格内容
                row.createCell(1).setCellValue(info.getString("name"));
                row.createCell(2).setCellValue(info.getString("signInTime"));
                row.createCell(3).setCellValue("已签到");
            }
            for(int i=0 ; i<noSignArray.size();i++){
                row = sheet[j-1].createRow(count + 1);
                count++;
                JSONObject info = noSignArray.getJSONObject(i);
                row.createCell(0).setCellValue(info.getString("sid"));   //设置单元格内容
                row.createCell(1).setCellValue(info.getString("name"));
                row.createCell(2).setCellValue(info.getString("signInTime"));
                row.createCell(3).setCellValue("未签到");
            }
            for(int i=0 ; i<leaveArray.size();i++){
                row = sheet[j-1].createRow(count + 1);
                count++;
                JSONObject info = leaveArray.getJSONObject(i);
                row.createCell(0).setCellValue(info.getString("sid"));   //设置单元格内容
                row.createCell(1).setCellValue(info.getString("name"));
                row.createCell(2).setCellValue(info.getString("signInTime"));
                row.createCell(3).setCellValue("请假");
            }
        }



        return wb;
    }


}
